<html>
<head>
<script src="../../resources/js-test.js"></script>
<style>
    html, body {
        margin: 0;
        padding: 0;
    }
    
    #test1 {
        margin: 100px;
        width: 200px;
        height: 200px;
        background: silver;
    }

    #test2 {
        margin: -90px 0 0 100px;
        width: 190px;
        height: 190px;
        border: 1px solid silver;
        padding: 4px;
    }

    #test2 > div {
        position: relative;
        height: 150px;
        width: 150px;
        overflow: auto;
        background: white;
    }

    #test2 > div > input {
        width: 80px;
        margin: 150px;
        border: 1px solid;
    }

    input, span {
        font-size: 14px;
        display: inline-block;
        height: 20px;
        overflow: hidden;
    }

</style>
<body>
    <div id="test1">
        <span>span</span>
    </div>
    <div id="test2">
        <div>
            <input type="text" value="input">
        </div>
    </div>
    <div id="console"></div>
</body>
<script>
    var TOLERANCE = 5;
    function isAcceptable(expected, result)
    {
        for (var i = 0; i < 4; i++) {
            if (Math.abs(expected[i] - result[i]) > TOLERANCE)
                return false;
        }
        return true;
    }
    
    function simulateElementClick(element, expected)
    {
        element.scrollIntoView(true);
        if (!window.eventSender)
            return 'This test requires eventSender';

        var result;
        function listener(event)
        {
            result = [event.offsetX, event.offsetY, event.layerX, event.layerY];
        }
            
        var rect = element.getBoundingClientRect();
        element.addEventListener('click', listener, false);
        eventSender.mouseMoveTo(rect.left + rect.width / 2, rect.top + rect.height / 2);
        eventSender.mouseDown();
        eventSender.mouseUp();
        element.removeEventListener('click', listener, false);

        if (result && isAcceptable(expected, result))
            return expected.join(', ');

        return result.join(', ');        
    }

    var testElement = document.getElementById('test1');
    var spanElement = testElement.getElementsByTagName('span')[0];
    var testElement2 = document.getElementById('test2');
    var inputElement = testElement2.getElementsByTagName('input')[0];

    shouldBe("simulateElementClick(testElement, [100, 100, 200, 200]);", "'100, 100, 200, 200'");
    shouldBe("simulateElementClick(spanElement, [16, 10, 16, 10]);", "'16, 10, 16, 10'");
    shouldBe("simulateElementClick(inputElement, [39, 9, 95, 10]);", "'39, 9, 95, 10'");
</script>
</html>
